<!-- eslint-disable vue/multi-word-component-names -->
<!-- @Author ： NWJ
        Version ： 1.0 -->

<template>
  <div class="wallet-container">
    <!-- 余额显示 -->
    <el-card class="balance-card">
      <div class="balance-header">
        <el-icon>
          <wallet />
        </el-icon>
        <span>我的钱包</span>
      </div>
      <div class="balance-amount">
        <span>当前余额：</span>
        <span class="amount">￥{{ balance.toFixed(2) }}</span>
      </div>
    </el-card>
    <span id="refresh" @click="onRefresh"><RefreshBtn></RefreshBtn></span>
    <!-- 充值与提现功能 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="action-card">
          <div class="action-header">
            <el-icon>
              <money />
            </el-icon>
            <span>充值</span>
          </div>
          <el-input v-model="rechargeAmount" placeholder="请输入充值金额" type="number" min="0">
            <template #append>元</template>
          </el-input>
          <el-button type="primary" @keyup.enter="startPay()" @click="startPay()" :disabled="!rechargeAmount">
            立即充值
          </el-button>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="action-card">
          <div class="action-header">
            <el-icon>
              <CreditCard />
            </el-icon>
            <span>提现</span>
          </div>
          <el-input v-model="withdrawAmount" placeholder="请输入提现金额" type="number" min="0">
            <template #append>元</template>
          </el-input>
          <el-button type="danger" :disabled="!withdrawAmount" @keys.space="handleWithdraw" @click="handleWithdraw">
            立即提现
          </el-button>
        </el-card>
      </el-col>
    </el-row>

    <!-- 交易记录 -->
    <el-card class="transaction-card">
      <div class="transaction-header">
        <el-icon>
          <list />
        </el-icon>
        <span>交易记录</span>
      </div>
      <el-table :data="transactions" style="width: 100%;user-select: none;">
        <template #empty>
          <div class="empty-state">
            <svg-icon name="empty-box" width="100px" height="100px" style="font-size: 60px">🤑</svg-icon>
            <p style="font-size: 14px; color: #999; text-align: center;">
             暂无交易记录
           </p>
         </div>
        </template>
        <el-table-column prop="orderNum" label="订单号" width="180" />
        <el-table-column prop="type" label="类型" width="120">
          <template #default="{ row }">
            <el-tag :type="row.type === '充值' ? 'success' : 'danger'">
              {{ row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="120">
          <template #default="{ row }">
            ￥{{ row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="日期" width="180" />
        <el-table-column prop="des" label="描述" />
      </el-table>
    </el-card>
  </div>
  <!-- 充值 Dialog -->
  <el-dialog v-model="dialogVisible" width="420px" style="user-select: none;" draggable :show-close=false>
    <template #title>
      <div class="custom-title">扫码进行支付</div>
    </template>
    <img :src=imageUrl>
  </el-dialog>
</template>

<script>
import { Wallet, Money, CreditCard, List } from '@element-plus/icons-vue'
import QRCode from 'qrcode'
import axios from 'axios'
import { showMsg } from '@/utils/showMsg'
import RefreshBtn from '@/components/RefreshBtn.vue'
import axiosService from '@/utils/request'

export default {
  components: {
    RefreshBtn,
    Wallet,
    Money,
    CreditCard,
    List
  },

  created()
  {
    this.balance = this.$store.state.user.money // 初始化余额
    this.init() // 初始化订单信息
  },

  data()
  {
    return {
      imageUrl: '',
      dialogVisible: false,
      balance: 0, // 余额
      rechargeAmount: '', // 充值金额
      withdrawAmount: '',  // 提现金额
      transactions: []// 交易记录
    }
  },
  methods: {
    // 数据初始化
    init()
    {
      axiosService.get(`/node/ordpays/getSome/id/${this.$store.state.user.id}`)
        .then(res =>
        {
          // 刷新订单信息
          for (let obj of res.data)
            obj.createdAt = obj.createdAt.slice(0, 10)
          this.transactions = res.data
        })
        .catch(e =>
        {
          showMsg('刷新失败', '登录凭证过期', 'warning')
        })
    },

    // 提现操作
    handleWithdraw()
    {
      const amount = parseFloat(this.withdrawAmount)
      if (amount > 0 && amount <= this.balance)
      {
        const timestamp = new Date().getTime()
        const orderNum = `ZGT${timestamp}`
        axiosService.post('/node/users/tx', {
          id: this.$store.state.user.id,
          amount: this.withdrawAmount,
          orderNum
        })
          .then(res =>
          {
            this.onRefresh()
            showMsg('提现结果', res.data, 'success')
          })
          .catch(e =>
          {
            showMsg('提现结果', e, 'error')
          })
      }
      else
        this.$message.warning('余额不足或输入金额无效！')
    },

    generateOrderNumber()
    {
      const timestamp = new Date().getTime()
      return `ZGP${timestamp}`
    },

    startPay()
    {
      axios.get('/node/users/pay')
        .then(res =>
        {
          const userId = this.$store.state.user.id
          const amount = this.rechargeAmount
          const orderNum = this.generateOrderNumber()
          const localIP = `${res.data.data}?orderNum=${orderNum}&amount=${amount}&userId=${userId}`
          try
          {
            QRCode.toDataURL(localIP, {
              color: {
                dark: '#425aef', // 设置二维码的前景色（二维码颜色）
                light: '#00000000' // 设置二维码的背景色
              },
              margin: 1, // 设置二维码的外边距
              scale: 10 // 设置二维码的缩放比例
            })
              .then(url =>
              {
                this.imageUrl = url // 将生成的二维码 URL 赋值给 imageUrl
              })
              .catch(err =>
              {
                // 捕获 QRCode.toDataURL 的错误
                showMsg('生成二维码失败:', err, 'error')
              })
          }
          catch (err)
          {
            // 捕获同步错误
            showMsg('生成二维码失败:', err, 'error')
          }
        })
        .catch(err =>
        {
          // 捕获 axios 请求的错误
          showMsg('支付请求失败:', err, 'error')
        })

      // 展示 Dialog
      this.dialogVisible = true
    },

    onRefresh()
    {
      this.init()
      axiosService.get(`/node/users/id/${this.$store.state.user.id}`)
        .then(res =>
        {
          // 刷新余额
          this.balance = res.data.money
        })
        .catch(e =>
        {
          showMsg('刷新失败', '登录凭证过期', 'warning')
        })
    }
  }
}
</script>

<style scoped>
.wallet-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  user-select: none;
}

.balance-card {
  margin-bottom: 20px;
}

.balance-header {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.balance-header .el-icon {
  margin-right: 10px;
}

.balance-amount {
  font-size: 24px;
  text-align: center;
}

.balance-amount .amount {
  color: #67c23a;
  font-weight: bold;
}

.action-card {
  margin-bottom: 20px;
}

/* 设置按钮为块级元素，并通过自动边距实现水平居中 */
.action-card .el-button {
  display: block; /* 将按钮显示模式改为块级元素 */
  width: fit-content; /* 根据内容调整宽度 */
  margin: 10px auto; /* 上下外边距为10px，左右设为auto实现水平居中 */
}

.action-header {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.action-header .el-icon {
  margin-right: 10px;
}

.transaction-card {
  margin-bottom: 20px;
  max-height: 40vh;
  overflow-y: scroll;
}

.transaction-header {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.transaction-header .el-icon {
  margin-right: 10px;
}

img { -webkit-user-drag: none; }

.custom-title {
  font-size: 30px;
  font-weight: 600;
  color: #858585;
  text-align: center;
}
#refresh {
  position: absolute;
  top: 8vh;
  right: 10px;
}
</style>
